package com.ledou44.ledourpc;

import com.ledou44.ledourpc.client.Client;
import com.ledou44.ledourpc.dto.LedouSradDTO;
import com.ledou44.ledourpc.dto.ServiceDTO;
import com.ledou44.ledourpc.service.Service;
import com.ledou44.ledourpc.sradenum.LedouSradEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ledou44
 * ledouRpc启动类：监听Spring容器初始化完成后启动
 */
@Component
public class ServiceStart implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private Service service;

    @Autowired
    private Client client;

    /**
     * spring容器将所有的Bean都初始化完成之后就会执行该方法
     * 作用是将服务提供者的服务端netty跑起来，并将其下所有实现类的接口和服务的ip/端口注册到服务注册发现中心
     * 看这个方法之前先看下面前置类
     * @see com.ledou44.ledourpc.configuration.LedouRpcBeanPostProcessor
     * @param event 事件
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        service.run();
        LedouSradDTO ledouSradDTO = new LedouSradDTO();
        List<ServiceDTO> serviceList = new ArrayList<>();
        ServiceBeanFactory.beanFactory.forEach((key,value) -> {
            ServiceDTO dto = new ServiceDTO();
            dto.setName(key);
            serviceList.add(dto);
        });
        ledouSradDTO.setServiceList(serviceList);
        ledouSradDTO.setType(LedouSradEnum.SERVICE_REGISTER.getCode());
        client.registerService(ledouSradDTO);
    }
}
